import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

// 1. 导入需要的路由组件
// import MyLogin from '@/views/Login/MyLogin.vue'
// import MyReg from '@/views/Reg/MyReg.vue'
// import MyMain from '@/views/Main/MyMain.vue'
// import MyHome from '@/views/Home/MyHome.vue'
// import UserInfo from '@/views/user/UserInfo.vue'
// import UserPwd from '@/views/user/UserPwd.vue'
// import UserAvatar from '@/views/user/UserAvatar.vue'
// import ArtCate from '@/views/Art/ArtCate.vue'
// import ArtList from '@/views/Art/ArtList.vue'

Vue.use(VueRouter)

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  { path: '/reg', component: () => import('@/views/Reg/MyReg.vue') },
  { path: '/login', component: () => import('@/views/Login/MyLogin.vue') },
  {
    path: '/',
    component: () => import('@/views/Main/MyMain.vue'),
    redirect: '/home',
    children: [
      { path: 'home', component: () => import('@/views/Home/MyHome.vue') },
      { path: 'user-info', component: () => import('@/views/user/UserInfo.vue') },
      { path: 'user-pwd', component: () => import('@/views/user/UserPwd.vue') },
      { path: 'user-avatar', component: () => import('@/views/user/UserAvatar.vue') },
      { path: 'art-cate', component: () => import('@/views/Art/ArtCate.vue') },
      { path: 'art-list', component: () => import('@/views/Art/ArtList.vue') }
    ]
  }
]

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  const token = store.getters.token
  if (to.path === '/reg' || to.path === '/login') {
    if (to.path === 'login' && token) {
      next('/')
    } else {
      next()
    }
  } else {
    // 访问的是有权限的页面，必须先登录，才能放行
    // 判断用户是否登录了
    if (token) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
